package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.bean.Employee;
import com.itheima.reggie.common.R;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: 许志民
 * Date: 2021-11-21
 */
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService es;
    @Autowired
    HttpServletRequest request;

    /**
     * 用户登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee){
//        ①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
//        ②. 根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = es.getOne(wapper);
//        ③. 如果没有查询到, 则返回登录失败结果
        if(one == null){
            return R.error("用户不存在");
        }
//        ④. 密码比对，如果不一致, 则返回登录失败结果
        if(!password.equals(one.getPassword())){
            return R.error("密码错误");
        }
//        ⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus() == 0){
            return R.error("用户已被禁用");
        }
//        ⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        HttpSession session = request.getSession();
        session.setAttribute("employee",one.getId());

        return R.success(one);
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(){
//        request.getSession().removeAttribute("employee");
        HttpSession session = request.getSession();
        session.setAttribute("employee",null);
        return R.success("操作成功");
    }

    /**
     * 首页分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        //如果页码和每页显示数超过了要显示
        int count = es.count();


        System.out.println(count);
        IPage<Employee> iPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        if(name != null){
            //如果数据存在则加上相应的条件
            wapper.like(Employee::getName,name);
        }
        IPage<Employee> page1 = es.page(iPage, wapper);
        //2.如果查询页码大于总页数时,设置当前页码为总页数
        if(iPage.getCurrent() > iPage.getPages()){
            iPage.setCurrent(iPage.getPages());
            page1 = es.page(iPage,wapper);
        }
//        log.info(b+"");
//        System.out.println(page1);
        return R.success(page1);
    }

    /**
     * 添加员工
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee,HttpServletRequest request){
        //先判断用户是否存在
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = es.getOne(wapper);
//        if(one != null){
//            return R.error("用户已存在");
//        }
        //如果用户不存在则补全字段
        //创建时间 创建用户id 更新用户id 初始化密码(123456)
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
//        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        boolean save = es.save(employee);
        return save ? R.success("添加成功") : R.error("添加失败");
    }

    /**
     * 修改状态以及修改用户信息
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){
        //如果是管理员id则不予以修改状态
        if(employee.getId() == 1){
            return R.error("管理员不可修改状态");
        }
        //根据用户的id修改状态
        //查询出该用户
        Employee esById = es.getById(employee.getId());
        if(esById == null){
            return R.error("用户不存在");
        }
        //用户存在则修改其数据  添加修改用户id
       // employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        //添加修改时间
//        employee.setUpdateTime(LocalDateTime.now());
        //添加状态
//        employee.setStatus(employee.getStatus());
        HttpSession session = request.getSession();
        Long emp = (Long) session.getAttribute("employee");
//        if(emp.longValue() != 1 ){
//            if(emp.longValue() != employee.getId().longValue()){
//                return  R.error("修改失败权限不足");
//            }
//        }
        if(emp.longValue() == 1l || emp.longValue() == employee.getId().longValue()){
            boolean b = es.updateById(employee);
            return b ? R.success("修改成功"):R.error("修改失败请重试");
        }
            return  R.error("普通用户不可修改除自己以外的用户");

    }

    /**
     * 修改用户信息时回显信息
     * @param request
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public R getById(HttpServletRequest request,@PathVariable Long userId){
        if(userId == null){
            return R.error("修改失败");
        }

        Employee byId = es.getById(userId);
        return R.success(byId);
    }
}
